package com.example.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.chrisplus.rootmanager.RootManager;
import com.chrisplus.rootmanager.container.Result;

public class Shell {
	/**
	 * RootManager实现
	 * @param cmd
	 * @return
	 */
	public static boolean runRootCmd(String cmd) {
		Result ret = RootManager.getInstance().runCommand(cmd);
		return ret.getResult();
	}
	/**
	 * 自己实现(具有返回值功能)
	 * @param cmd
	 * @return
	 */
	public static int runRootCmd2(String cmd) {
		if(cmd == null) return -1;
		Process process = null;
		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd);
			os.writeBytes("\nexit\n");
			os.flush();
			process.waitFor();
			return process.exitValue();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (Exception e) {
			}
			if (process != null)
				process.destroy();
		}
		return -1;
	}
	/**
	 * 执行普通命令
	 */
	public static void runCmd(String cmd) {
		try {
			Process exec = Runtime.getRuntime().exec(cmd);
			exec.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    /**
     * 执行命令，并返回所有结果行
     */
    public static List<String> runCmdAndGetResult(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
            
            InputStream is = p.getInputStream();
            BufferedReader reader2 = new BufferedReader(new InputStreamReader(is));
            List<String> list = new ArrayList<String>(128);
            String line = null;
            while((line = reader2.readLine()) != null) {
                list.add(line);
            }
            reader2.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
	public static void kill(String processName){
		List<String> lines = runCmdAndGetResult("ps");
		for(String l : lines){
			if(l.endsWith(processName)){
				String[] ss = l.split("\\s+");
				String pid = ss[1];
				runRootCmd2("kill -9 "+pid);
			}
		}
		
	}
}
